package cn.dengta.context.web;

import cn.dengta.common.context.Env;
import cn.dengta.context.SessionContext;
import cn.dengta.context.model.*;
import cn.dengta.webapp.base.util.ConvertFilterUtil;
import cn.dengta.webapp.base.vo.UserIdEncode;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ValueFilter;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * 在对外输出前，对 用户ID 进行编码处理
 *
 * @see UserIdConverter#convert(String)
 */
public class UserIdEncodeFilter implements ValueFilter {

	public static final UserIdEncodeFilter INSTANCE = new UserIdEncodeFilter();

	public static final WesKit[] GOLD_WESKIT = new WesKit[] { };

	@Override
	public Object process(Object o, String name, Object value) {
		if (value instanceof Long) {
			if ("userId".equals(name) || name.endsWith("UserId") || ("id".equals(name) && UserIdEncode.class.isAssignableFrom(o.getClass()))) {
				return Member.encode((Long) value);
			}
		}
		SessionContext sessionContext = RequestContextImpl.get().sessionContext();
		final WesKit wesKit = sessionContext.getWesKit();
		final boolean contains = ArrayUtils.contains(GOLD_WESKIT, wesKit);
		if (contains && value instanceof String && StringUtils.isNotEmpty(value.toString())) {
			final Language language = sessionContext.getLanguage();
			if (language != null) {
				switch (language) {
					case en -> value = StringUtils.replaceIgnoreCase(value.toString(), "diamond", "coin");
					case zh -> value = StringUtils.replace(value.toString(), "鉆石", "金幣");
					case zh_CN -> value = StringUtils.replace(value.toString(), "钻石", "金币");
				}
			}
		}
		// 性别默认头像
		if (value instanceof String && "avatar".equals(name)) {
			// 检查是否以http或https开头
			value = ConvertFilterUtil.convertGenderUrl(wesKit, value.toString());
		}
		if (Env.inProduction() && value instanceof String) {
			return ConvertFilterUtil.convertDomainUrl(value.toString());
		}
		return value;
	}

	public static String toJSONString(Object obj) {
		return JSONObject.toJSONString(obj, INSTANCE, SerializerFeature.DisableCircularReferenceDetect);
	}

}
